class Cpanel::BaseController < ActionController::Base
  layout 'cpanel'
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  #protect_from_forgery with: :exception
  protect_from_forgery with: :exception

  include Pundit
  rescue_from Pundit::NotAuthorizedError, with: :admin_not_authorized

  before_action :authenticate_admin!
  # devise 验证用户以及传递验证的字段(mobile,默认为：email)
  before_action :configure_permitted_parameters, if: :devise_controller?

  # pundit 权限验证
  before_action :pundit_authorized

  # rescue_from ::Exception, with: :error_occurred

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_in, keys: [:email])
  end

  # customize pundit user, default it will call current_user
  def pundit_user
    current_admin
  end

  def policy(record)
    super(record)
  end

  def pundit_authorized
    authorize self.class.name.sub('Controller', '').split('::').map(&:to_sym) unless current_admin.is_superadmin?
  end

  private

  def admin_not_authorized
    Rails.logger.debug '权限不足'
    flash[:notice] = '权限不足'
    # render js: 'CPANEL.alter("权限不足");'
    redirect_to(no_authorized_cpanel_roots_path)
  end
end
